package com.dts.utils;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 */
@Component
public class RedisUtils
{
    @Autowired
    private RedisTemplate<String, Object>   redisTemplate;
    /**  默认过期时长，单位：秒 */
    public final static long                DEFAULT_EXPIRE = 60 * 60 * 24;

    public void set(String key, Object value)
    {
        set(key, value, DEFAULT_EXPIRE);
    }

    public void set(String key, Object value, long expire)
    {
        redisTemplate.opsForValue().set(key, toJson(value));
        redisTemplate.expire(key, expire, TimeUnit.SECONDS);
    }
    public String get(String key)
    {
        return redisTemplate.opsForValue().get(key).toString();
    }
    public <T> T get(String key, Class<T> clazz)
    {
        String value = redisTemplate.opsForValue().get(key).toString();
        return value == null ? null : fromJson(value, clazz);
    }
    public void delete(String key)
    {
        redisTemplate.delete(key);
    }
    private String toJson(Object object)
    {
        if (object instanceof Integer || object instanceof Long || object instanceof Float || object instanceof Double
                || object instanceof Boolean || object instanceof String)
        {
            return String.valueOf(object);
        }
        return JSON.toJSONString(object);
    }
    private <T> T fromJson(String json, Class<T> clazz)
    {
        return JSON.parseObject(json, clazz);
    }
}